/*
 ============================================================================
 Name		: ontact.cpp
 Author	  : jshuabo.com
 Version	 : 1.0
 Copyright   : jshuabo.com,All Right Reserved!
 Description : Contact implementation
 ============================================================================
 */

#include "Contact.h"

_LIT(KSpalsh,"#");


Contact::Contact()
{ 
	iNullBuf = NULL;
}

Contact::~Contact()
{
	TInt count = iContactInfoArray.Count();
	if(count > 0)
	{
		for(TInt item = count-1;item>=0;item--)
		{
			HBufC* pTempBuf = iContactInfoArray[item];
			if(pTempBuf)
			{
				delete pTempBuf;
				iContactInfoArray.Remove(item);
			}
		}
	}
	iContactInfoArray.Close();
	
	if(iNullBuf)
	{
		delete iNullBuf;
		iNullBuf = NULL;
	}
}

Contact* Contact::NewLC()
{
	Contact* self = new (ELeave) Contact();
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
}

Contact* Contact::NewL()
{
	Contact* self = Contact::NewLC();
	CleanupStack::Pop(); // self;
	return self;
}

void Contact::ConstructL()
{	 
	for(TInt item = 0;item<KFieldNumber;item++)
	{
//		HBufC* pTempHBuf = HBufC::NewL(KFieldIntialLength);
		HBufC* pTempHBuf = NULL;
		iContactInfoArray.Append(pTempHBuf);
	}
	iNullBuf = HBufC::NewL(KFieldIntialLength);
	TPtr ptr(iNullBuf->Des());
	ptr.Append(KNullDesC);	
	
}

TBool Contact::SetContactFieldByIndex(const TInt aIndex,const TDesC& aFieldDesC)
{
	if(aIndex < 0 ||aIndex > KFieldNumber -1)
	{		
		return EFalse;
	}
	HBufC* pTempBuf = iContactInfoArray[aIndex];	
	
	if(pTempBuf)
	{
		 TInt8  pLength = pTempBuf->Length();
		 HBufC* pNewBuf = HBufC::NewL(pLength + aFieldDesC.Length() + 5);
		 TPtr   pNewBufPtr(pNewBuf->Des()); 
		 pNewBufPtr.Append(*pTempBuf);	
		 pNewBufPtr.Append(KSpalsh);
		 pNewBufPtr.Append(aFieldDesC);
		 
		 delete pTempBuf;
		 iContactInfoArray[aIndex] = pNewBuf;
		 
	}else 
	{
		iContactInfoArray[aIndex] = HBufC::NewL(aFieldDesC.Length());	
		TPtr  ptr(iContactInfoArray[aIndex]->Des());
		ptr.Append(aFieldDesC);
	}	
}


TDesC&  Contact::GetContactFieldByIndex( TInt aIndex)
{
	if(aIndex < 0 ||aIndex > KFieldNumber -1)
	{		
		return *iNullBuf;
	}
	HBufC* pTempBuf = iContactInfoArray[aIndex];
	if(pTempBuf)
	{
		return *pTempBuf;
	}
	else
	{
		return *iNullBuf;
	}
}
